﻿using System;
using System.Configuration;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class ModalProductControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        public void SetControlEnabledState(bool bstate = false)
        {
            RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelProduct.ContentTemplateContainer, bstate);
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            if (hfRedirectURL.Value.Length > 0)
            {
                var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
                string updatedQueryString = "?" + nameValues.ToString();
                string url = Request.Url.AbsolutePath;
                if(url.Contains("RSEstimateDetail"))
                {
                    nameValues.Set("tabindex", "2");
                    url = url + updatedQueryString;
                    Response.Redirect(url);
                }
                else if(url.Contains("RSWorkOrderDetail"))
                {
                    url = url + updatedQueryString;
                    Response.Redirect(url);
                }
                else
                {
                    Response.Redirect(hfRedirectURL.Value);
                }
                
            }
            else
            {
                mpeModalProduct.Hide();
            }
        }
        protected void btnEditProduct_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                btnEditProduct.Visible = false;
                btnSaveProduct.Visible = true;
                btnDeleteProduct.Visible = true;
                SetControlEnabledState(true);
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                btnEditProduct.Visible = false;
                btnSaveProduct.Visible = false ;
                btnDeleteProduct.Visible = false;
                SetControlEnabledState(false);
            }
        }

        protected void btnSaveProduct_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                int CompanyId = userIdentity.RSCompanyId;

                string ProductName = txtProductName.Text;
                string ProductDesc = txtProductDesc.Text;
                int QuantityPerUnit = txtQuantityPerUnit.Text == "" ? 0 : Convert.ToInt32(txtQuantityPerUnit.Text);
                Single UnitPrice = txtUnitPrice.Text == "" ? 0 : Convert.ToSingle(txtUnitPrice.Text);
                int UnitsInStock = txtUnitsInStock.Text == "" ? 0 : Convert.ToInt32(txtUnitsInStock.Text);
                int UnitsOnOrder = txtUnitsOnOrder.Text == "" ? 0 : Convert.ToInt32(txtUnitsOnOrder.Text);
                int ReorderLevel = txtReorderLevel.Text == "" ? 0 : Convert.ToInt32(txtReorderLevel.Text);
                string Manufacture = txtManufacture.Text;
                string ModelNo = txtModelNo.Text;
                string SerialNo = txtSerialNo.Text;
                string ProductCode = txtProductCode.Text;
                int ParentId = txtParentId.Text == "" ? 0 : Convert.ToInt32(txtParentId.Text);
                int SupplierId = txtSupplierId.Text == "" ? 0 : Convert.ToInt32(txtSupplierId.Text);
                int ProductId = txtProductId.Text == "" ? 0 : Convert.ToInt32(txtProductId.Text);

                bool isDiscontinued = false;
                if (chkDiscontinued.Checked == true)
                    isDiscontinued = true;
                bool isEquipment = false;
                if (chkIsEquipment.Checked == true)
                    isEquipment = true;


                SqlCommand sqlCmd = new SqlCommand();

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ProductName", SqlDbType.NVarChar, 100, ParameterDirection.Input, ProductName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Manufacture", SqlDbType.NVarChar, 100, ParameterDirection.Input, Manufacture);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ModelNo", SqlDbType.NVarChar, 25, ParameterDirection.Input, ModelNo);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@SerialNo", SqlDbType.NVarChar, 25, ParameterDirection.Input, SerialNo);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ProductCode", SqlDbType.NVarChar, 25, ParameterDirection.Input, ProductCode);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ProductDesc", SqlDbType.NVarChar, -1, ParameterDirection.Input, ProductDesc);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@QuantityPerUnit", SqlDbType.Int, 0, ParameterDirection.Input, QuantityPerUnit);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@UnitPrice", SqlDbType.Money, 0, ParameterDirection.Input, UnitPrice);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@UnitsInStock", SqlDbType.Int, 0, ParameterDirection.Input, UnitsInStock);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@UnitsOnOrder", SqlDbType.Int, 0, ParameterDirection.Input, UnitsOnOrder);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReorderLevel", SqlDbType.Int, 0, ParameterDirection.Input, ReorderLevel);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ParentId", SqlDbType.Int, 0, ParameterDirection.Input, ParentId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@SupplierId", SqlDbType.Int, 0, ParameterDirection.Input, SupplierId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ProductId", SqlDbType.Int, 0, ParameterDirection.Input, ProductId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Discontinued", SqlDbType.Bit, 0, ParameterDirection.Input, isDiscontinued);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@IsEquipment", SqlDbType.Bit, 0, ParameterDirection.Input, isEquipment);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveInventory");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);

                lblMessage.Text = "Item Successfully Saved!";
                lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                btnEditProduct.Visible = false;
                btnSaveProduct.Visible = false;
                btnDeleteProduct.Visible = false;
                SetControlEnabledState(false);
                hfRedirectURL.Value = Request.RawUrl;
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                btnEditProduct.Visible = false;
                btnSaveProduct.Visible = false;
                btnDeleteProduct.Visible = false;
                SetControlEnabledState(false);
                hfRedirectURL.Value = "";
            }
        }
        protected void btnDeleteProduct_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int companyid = userIdentity.RSCompanyId;
                int productid = txtProductId.Text == "" ? 0 : Convert.ToInt32(txtProductId.Text);

                if (companyid > 0 && productid > 0)
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@productid", SqlDbType.Int, 0, ParameterDirection.Input, productid);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
                    SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblWorkOrderPart WHERE ProductId=@productid AND CompanyId=@companyid; DELETE FROM rs_tblInventory WHERE ProductId=@productid AND CompanyId=@companyid");
                    SQLHelper.ExecuteScalarCmd(sqlCmd);
                    int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                    lblMessage.Text = "Item deleted successfully!";
                    lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                    btnEditProduct.Visible = false;
                    btnSaveProduct.Visible = false;
                    btnDeleteProduct.Visible = false;
                    SetControlEnabledState(false);
                    hfRedirectURL.Value = Request.RawUrl;
                }
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                btnEditProduct.Visible = false;
                btnSaveProduct.Visible = false;
                btnDeleteProduct.Visible = false;
                SetControlEnabledState(false);
                hfRedirectURL.Value = "";
            }
        }

        public void ShowModal(int companyid, int productid, bool isequipment = false)
        {
            hfRedirectURL.Value = "";
            lblMessage.Text = "Inventory Item";
            if (LoadProductDataByID(companyid, productid, isequipment))
            {
                btnEditProduct.Visible = true;
                btnSaveProduct.Visible = false;
                btnDeleteProduct.Visible = false;
                SetControlEnabledState(false);
            }
            else
            {
                btnEditProduct.Visible = false;
                btnSaveProduct.Visible = true;
                btnDeleteProduct.Visible = false;
                SetControlEnabledState(true);
            }
            mpeModalProduct.Show();
        }
        private bool LoadProductDataByID(int companyid, int productid, bool isequipment)
        {
            bool bHasValue = false;
            txtProductId.Text = productid.ToString();
            if (isequipment)
                lblMessage.Text = "Equipment Inventory Item";
            else
                lblMessage.Text = "Part Inventory Item";

            //pnlIsEquipment.Visible = isequipment;

            String strSQL = "SELECT ProductId,ProductName,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,ProductDesc,Manufacture,Discontinued,ModelNo,SerialNo,ProductCode,ParentId,SupplierID,CompanyId, IsEquipment FROM rs_tblInventory where IsEquipment=@isequipment and ProductId=@productid and companyid=@companyid";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@isequipment";
            param.Value = isequipment;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@productid";
            param.Value = productid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if(myDataReader.HasRows)
            {
                myDataReader.Read();
                txtProductName.Text = myDataReader["ProductName"].ToString();
                txtQuantityPerUnit.Text = myDataReader["QuantityPerUnit"].ToString();
                txtUnitPrice.Text = Convert.ToSingle(myDataReader["UnitPrice"]).ToString();
                txtUnitsInStock.Text = myDataReader["UnitsInStock"].ToString();
                txtUnitsOnOrder.Text = myDataReader["UnitsOnOrder"].ToString();
                txtReorderLevel.Text = myDataReader["ReorderLevel"].ToString();
                txtProductDesc.Text = myDataReader["ProductDesc"].ToString();
                txtManufacture.Text = myDataReader["Manufacture"].ToString();
                txtModelNo.Text = myDataReader["ModelNo"].ToString();
                txtSerialNo.Text = myDataReader["SerialNo"].ToString();
                txtProductCode.Text = myDataReader["ProductCode"].ToString();
                txtParentId.Text = myDataReader["ParentId"].ToString();
                txtSupplierId.Text = myDataReader["SupplierID"].ToString();

                if (myDataReader["Discontinued"] != DBNull.Value)
                    chkDiscontinued.Checked = Convert.ToBoolean(myDataReader["Discontinued"].ToString());
                else
                    chkDiscontinued.Checked = false;

                if (myDataReader["IsEquipment"] != DBNull.Value)
                    chkIsEquipment.Checked = Convert.ToBoolean(myDataReader["IsEquipment"].ToString());
                else
                    chkIsEquipment.Checked = false;
                
                bHasValue = true;
            }
            myConnection.Close();
            return bHasValue;
        }



    }
}